package com.credithc.signature.core.util;

import com.itextpdf.text.pdf.BaseFont;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.ByteArrayInputStream;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;

/**
 * PDF生成工具类
 */
public class PdfGenerator {

	/**
	 * 生成pdf数据到特定流
	 * @param pdfParams
	 * @param out
	 * @throws Exception
	 */
	public static void generate(String pdfParams, OutputStream out)
			throws Exception {

		DocumentBuilder builder = DocumentBuilderFactory.newInstance()
				.newDocumentBuilder();
		Document doc = builder.parse(new ByteArrayInputStream(pdfParams
				.getBytes(StandardCharsets.UTF_8)));
		ITextRenderer renderer = new ITextRenderer();
		// 解决中文支持问题

		ITextFontResolver fontResolver = renderer.getFontResolver();
		fontResolver.addFont("/usr/share/fonts/ttc/SimSun.ttc",BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
		try {
			renderer.setDocument(doc, null);
			renderer.layout();
			renderer.createPDF(out);
		} catch (Exception e) {
			throw new Exception(e.getMessage());
		}
	}
}